package test.socket;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
	
	public static void main(String[] args) {
		try {
			@SuppressWarnings("resource")
			ServerSocket ss = new ServerSocket(6666);
			System.out.println("server is listening on port 6666...");
			while(true) {
				Socket s = ss.accept();
				System.out.println("socket " + s.getPort() + " connect...");
				InputStream is = s.getInputStream();
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
//				String str = null;
//				while(!(str = br.readLine()).equals("bye")) {
//					System.out.println(str);
//				}
//				s.close();
				while(true) {
					String text = br.readLine();
					System.out.println(text);
					if(text.equals("bye")) {
						break;
					}
				}
				s.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static String inputStream2String(InputStream is) throws IOException{ 
		ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
		int i=-1; 
		while((i=is.read())!=-1){ 
			baos.write(i); 
		} 
        return baos.toString(); 
	}

}
